package com.jinzecloud.reportapproval.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.config.Configure;
import com.jinzecloud.reportapproval.bean.AuthenticationTask;
import com.jinzecloud.reportapproval.bean.ProductSpecification;
import com.jinzecloud.reportapproval.dto.AdminDto;
import com.jinzecloud.reportapproval.dto.AuditParam;
import com.jinzecloud.reportapproval.dto.DataStagingParam;
import com.jinzecloud.reportapproval.enums.AuditRoleEnums;
import com.jinzecloud.reportapproval.enums.StateEnum;
import com.jinzecloud.reportapproval.enums.TableEnums;
import com.jinzecloud.reportapproval.utils.*;
import com.jinzecloud.reportapproval.vo.AuthenticationTaskVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.StandardCopyOption;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.jinzecloud.reportapproval.mapper.SampleTransferMapper;
import com.jinzecloud.reportapproval.bean.SampleTransfer;
import com.jinzecloud.reportapproval.service.SampleTransferService;

import javax.servlet.http.HttpServletRequest;


@Service("sampleTransferService")
public class SampleTransferServiceImpl extends ServiceImpl<SampleTransferMapper, SampleTransfer> implements SampleTransferService {

    @Autowired
    private FileUploadUtil fileUploadUtil;
    @Autowired
    private HttpServletRequest request;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SampleTransfer> sampleTransferQueryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        sampleTransferQueryWrapper.like(StrUtil.isNotBlank(key), "sample_number", key)
                .or().like(StrUtil.isNotBlank(key), "prototype_trademark", key)
                .or().like(StrUtil.isNotBlank(key), "detection_site", key)
                .or().like(StrUtil.isNotBlank(key), "inspector", key)
                .or().like(StrUtil.isNotBlank(key), "sample_collection_site", key);
        IPage<SampleTransfer> page = this.page(
                new Query<SampleTransfer>().getPage(params),
                sampleTransferQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public Object auditList(DataStagingParam param) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LambdaQueryWrapper<SampleTransfer> queryWrapper = new LambdaQueryWrapper<>();
        List<AdminDto> adminDto = AuditUtil.getAdminDto(authentication.getName());
        Set<Integer> roleSet = adminDto.stream().map(a -> StateEnum.getStateEnumByAuditRole(a.getRoleCode()).getState()).collect(Collectors.toSet());
        roleSet.remove(StateEnum.UN_SUBMIT.getState());
        queryWrapper.in(SampleTransfer::getStatus, roleSet);
        return page(new Page<>(param.getPageNo(), param.getPageSize()), queryWrapper);
    }

    @Override
    public R audit(AuditParam auditParam) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        List<AdminDto> adminDos = AuditUtil.getAdminDto(authentication.getName());
        if (CollectionUtil.isEmpty(adminDos)) return R.error("您没有审核权限！");
        SampleTransfer sampleTransfer = this.getById(auditParam.getId());
        int state = sampleTransfer.getStatus();
        if (!auditParam.isState()) {
            updateById(sampleTransfer.setStatus(StateEnum.APPROVAL_NOT_PASS.getState())
                    .setAuditOpinion(auditParam.getAuditOpinion())
                    .setAuditDate(DateUtil.date().toDateStr()));
            return R.ok();
        }
        StateEnum currentAuditState = AuditUtil.getStateText(TableEnums.SAFETY_ASSESSMENT.getTableName(), state);
        Integer nextAuditStateIndex = AuditUtil.getNextAuditState(TableEnums.SAFETY_ASSESSMENT.getTableName(), state, adminDos.stream().map(AdminDto::getRoleCode).toList());
        AdminDto adminDto = adminDos.stream().filter(a -> StrUtil.equals(a.getRoleCode(), currentAuditState.getAuditRole()))
                .findFirst().orElse(null);
        if (adminDto == null || nextAuditStateIndex == null) return R.error("您没有审核权限！");
        if (StrUtil.equals(adminDto.getRoleCode(), AuditRoleEnums.CHECKER_PERSON.getCode())) sampleTransfer.setSampleManager(adminDto.getAdSignature());
        if (StrUtil.equals(adminDto.getRoleCode(), AuditRoleEnums.CHECKER_PERSON.getCode())) sampleTransfer.setProjectLeader(adminDto.getAdSignature());
        sampleTransfer.setStatus(nextAuditStateIndex)
                .setAuditOpinion(auditParam.getAuditOpinion())
                .setAuditDate(DateUtil.date().toDateStr());
        updateById(sampleTransfer);
        return R.ok();
    }

    @Override
    public String export(Integer id) throws ParseException {
        SampleTransfer sampleTransfer = getById(id);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        if (sampleTransfer != null) {
            String format = simpleDateFormat.format(simpleDateFormat1.parse(sampleTransfer.getStartingTime()));
            String format1 = simpleDateFormat.format(simpleDateFormat1.parse(sampleTransfer.getEndTime()));
            String format3 = simpleDateFormat.format(simpleDateFormat1.parse(sampleTransfer.getStartingTime1()));
            String format4 = simpleDateFormat.format(simpleDateFormat1.parse(sampleTransfer.getEndTime1()));
            sampleTransfer.setStartingTime(format).setEndTime(format1).setEndTime1(format4).setStartingTime1(format3);
        }
        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(sampleTransfer));
        File tempFile = WordUtil.getWordFile("template/sampletransfer.docx", data, Configure.builder().useSpringEL());
        String fileName = "样品传递卡";
        String uploadDirectory = fileUploadUtil.getUploadFilePath("temp");
        String filePath = uploadDirectory + sampleTransfer.getSampleNumber() + fileName;
        String savePath = RequestUtils.getBasePath(request) + "upload/temp/" + sampleTransfer.getSampleNumber() +fileName;
        FileUtil.copyFile(tempFile.toPath(), new File(filePath + ".docx").toPath(), StandardCopyOption.REPLACE_EXISTING);
        PDFUtil.WordToPdf(tempFile, new File(filePath + ".pdf"));
        this.update(new LambdaUpdateWrapper<SampleTransfer>().set(SampleTransfer::getWordPath, savePath + ".docx").set(SampleTransfer::getPdfPath, savePath + ".pdf").eq(SampleTransfer::getId, id));
        return RequestUtils.getBasePath(request) + "upload/temp/" + sampleTransfer.getSampleNumber() + fileName + ".pdf";
    }

    public String exportWord(Integer id) throws ParseException {
        SampleTransfer sampleTransfer = getById(id);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        if (sampleTransfer != null) {
            String format = simpleDateFormat.format(simpleDateFormat1.parse(sampleTransfer.getStartingTime()));
            String format1 = simpleDateFormat.format(simpleDateFormat1.parse(sampleTransfer.getEndTime()));
            String format3 = simpleDateFormat.format(simpleDateFormat1.parse(sampleTransfer.getStartingTime1()));
            String format4 = simpleDateFormat.format(simpleDateFormat1.parse(sampleTransfer.getEndTime1()));
            sampleTransfer.setStartingTime(format).setEndTime(format1).setEndTime1(format4).setStartingTime1(format3);
        }
        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(sampleTransfer));
        File tempFile = WordUtil.getWordFile("template/sampletransfer.docx", data, Configure.builder().useSpringEL());
        String fileName = "样品传递卡";
        String uploadDirectory = fileUploadUtil.getUploadFilePath("temp");
        String filePath = uploadDirectory + sampleTransfer.getSampleNumber() + fileName;
        String savePath = RequestUtils.getBasePath(request) + "upload/temp/" + sampleTransfer.getSampleNumber() +fileName;
        FileUtil.copyFile(tempFile.toPath(), new File(filePath + ".docx").toPath(), StandardCopyOption.REPLACE_EXISTING);
        PDFUtil.WordToPdf(tempFile, new File(filePath + ".pdf"));
        this.update(new LambdaUpdateWrapper<SampleTransfer>().set(SampleTransfer::getWordPath, savePath + ".docx").set(SampleTransfer::getPdfPath, savePath + ".pdf").eq(SampleTransfer::getId, id));
        return RequestUtils.getBasePath(request) + "upload/temp/" + sampleTransfer.getSampleNumber() + fileName + ".docx";
    }

    @Override
    public String viewPdf(Integer id) throws ParseException {
        String export = export(id);
        return export;
    }

    @Override
    public R saveSampleTransfer(SampleTransfer sampleTransfer) {
        QueryWrapper<SampleTransfer> sampleTransferQueryWrapper = new QueryWrapper<>();
        sampleTransferQueryWrapper.eq("sample_number", sampleTransfer.getSampleNumber());
        if (list(sampleTransferQueryWrapper).size() >= 1){
            return R.error("该编号已存在，请重新输入");
        }else {
            save(sampleTransfer);
            return R.ok();
        }
    }

    @Override
    public String viewWord(Integer id) throws ParseException {
        String export = exportWord(id);
        return export;
    }

}